/* FsUrl.java Copyright 2010 by Jo Pol
 *
 * This file is part of fs-thumbs.
 *
 * fs-thumbs  is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * fs-thumbs  is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with BobbinWork.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.fs_thumbs;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

/**
 * @author Jo Pol
 */
public class FsUrl {

	private final String collectionId;
	private final URL url;
	static final String FIRST_ROW = "start=0";
	static final String MAX_ROWS = "rows=2147483647";
	static final String ALL_ROWS = "?" + FIRST_ROW + "&" + MAX_ROWS;

	public FsUrl(final String collection, final String waypoint) throws MalformedURLException {

		if (!collection.matches("[0-9]+") || !waypoint.matches("[0-9]+"))
			throw new IllegalArgumentException(MessageFormat.format("waypoint [{1}] or collection [{0}] not numeric",
					collection, waypoint));
		this.collectionId = collection;
		url = new URL("http://pilot.familysearch.org/recordsearch/v1/collection/fs:"//
				+ getCollectionId() + "/waypoint/" + waypoint + ALL_ROWS);
	}

	public FsUrl(final String url) throws MalformedURLException {

		final URL url2 = new URL(url);
		if (!url2.getPath().matches(".*/fs:([0-9]+)/waypoint/([0-9]+)"))
			throw new IllegalArgumentException("url path should end with 'fs:99999/waypoint/99999'");
		this.url = new URL(url + addQueryDefaults(url2.getQuery()));
		this.collectionId = this.url.getPath().replaceAll(".*/fs:", "").replaceAll("/waypoint/.*", "");
	}

	private static String addQueryDefaults(final String query) throws MalformedURLException {

		if (query == null) {
			return ALL_ROWS;
		} else if (query.contains("start=")) {
			if (query.contains("rows=")) {
				return "";
			} else {
				return "&" + MAX_ROWS;
			}
		} else if (query.contains("rows=")) {
			return "&" + FIRST_ROW;
		}
		return "&" + FIRST_ROW + "&" + MAX_ROWS;
	}

	public URL toURL() {
		return url;
	}

	public final String toString() {
		return url.toString();
	}

	public String getCollectionId() {
		return collectionId;
	}
}
